package com.java.code.kafka;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.utils.Utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 用于分区
 *
 * @author weichuanyuan
 * @version 1.0
 * @date 2021/10/23 20:12
 */
public class MyPartitioner implements Partitioner {

    private AtomicInteger counter = new AtomicInteger(0);

    /**
     * 返回分区号
     *
     * @param topic      topic
     * @param key        key
     * @param keyBytes   key的字节数
     * @param value      value
     * @param valueBytes value的字节数
     * @param cluster    集群信息
     * @return 分区号
     */
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        //先获取集群的分区数
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        int numPartitions = partitions.size();

        if (keyBytes == null) {
            int increment = counter.getAndIncrement();
            //拿这个值模上分区数
            // increment & Integer.MAX_VALUE 保证是个正数
            return (increment & Integer.MAX_VALUE) % numPartitions;
        } else {
            return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
        }
    }

    @Override
    public void close() {
        System.out.println("MyPartitioner#close.");
    }

    @Override
    public void configure(Map<String, ?> map) {
        System.out.println("MyPartitioner#configure.");
    }
}
